import { materialTypeAtom } from '@/jotais/enum';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { useAtom } from 'jotai';
import { useMemo } from 'react';

const useMaterial = () => {
  const [materialType, setMaterialType] = useAtom(materialTypeAtom);

  useAsyncEffect(async () => {
    if (materialType?.length === 0) {
      const res = await request({
        url: '/datas/material/type/list',
        method: 'GET',
      });
      setMaterialType(
        res?.map?.((item: any) => ({
          label: item.name,
          value: item.id,
        })),
      );
    }
  }, []);

  const materialTypeMap = useMemo(() => {
    return materialType.reduce((acc, item) => {
      acc[item.value] = item.label;
      return acc;
    }, {} as any);
  }, [materialType]);

  return {
    materialTypeOptions: materialType,
    materialTypeMap,
  };
};

export default useMaterial;
